<template>
	<view class="store-settings">
		<view class="toggle-section">
			<text>启用抽奖</text>
			<view class="switch-container" @tap="toggleLottery">
				<switch :checked="enableLottery" class="switch-checkbox" />
				<view class="slider round" :class="{'active': enableLottery}"></view>
			</view>
		</view>
		<view class="form-section">
			<text>门店信息</text>
			<button @tap="navigateToEditStoreInfo" style="width: 80px;margin-right: 5px;">完善</button>
		</view>
		<view class="form-section">
			<text>联系电话</text>
			<text v-if="!contactPhoneEditMode" style="margin-left: 30px;">{{ tempContactPhone || '未填写' }}</text>
			<input v-else v-model="tempContactPhone" type="text" class="form-input" />
			<button @tap="toggleEditMode('contactPhone')" style="width: 80px;margin-right: 5px;">
				{{ contactPhoneEditMode ? '保存' : '完善' }}
			</button>
		</view>
		<view class="form-section">
			<text>门店地址</text>
			<text v-if="!storeAddressEditMode" style="margin-left: 30px;">{{ tempStoreAddress || '未填写' }}</text>
			<input v-else v-model="tempStoreAddress" type="text" class="form-input" />
			<button @tap="toggleEditMode('storeAddress')" style="width: 80px;margin-right: 5px;">
				{{ storeAddressEditMode ? '保存' : '完善' }}
			</button>
		</view>

		<!-- 抽奖转盘 -->
		<view class="roulette-section">
			<view class="prize-grid">
				<view v-for="(prize, index) in prizes" :key="index" class="prize-item"
					:class="{ 'highlight': highlightedIndex === index }">
					<button  class="prize-content"  @click="handlePrizeClick(index, prize)">
						<image :src="prize.icon" mode="aspectFit" class="prize-img"/>
						<text class="prize-name">{{ prize.name }}</text>
				    </button>		     
					</view>
					<uni-popup ref="popupBottom" type="bottom" border-radius="10px 10px 0 0">
					<view class="popup-content">
					    <view class="form-item">
					      <text>奖品名称</text>
					      <input v-model="prizeName" placeholder="请输入奖品名称" />
					    </view>
					    <view class="form-item">
					      <text>最低</text>
					      <input v-model="minAmount" placeholder="请输入最低金额" />
					    </view>
					    <view class="form-item">
					      <text>最高</text>
					      <input v-model="maxAmount" placeholder="请输入最高金额" />
					    </view>
					    <view class="form-item">
					      <text>自动返现</text>
					      <switch :checked="true"></switch>
					    </view>
					    <view class="form-item">
					      <text>设为默认奖品</text>
					      <switch :checked="true"></switch>
					    </view>
					    <button type="primary" @click="confirmSetPrizeCon">确认</button>
					    <button @click="closePopup">取消</button>
					  </view>
					</uni-popup>
			</view>
			<!-- 中心按钮 -->
			<button @tap="spinRoulette" class="spin-button">点击开始</button>
		</view>
		<!-- 设置容器 -->
		<view class="form-section">
			<text>最晚处理审核时间</text>
			<input type="number" v-model="maxSubmissionTimeHours" style="margin-left: 210px; width: 50px;" />
		</view>
		<view class="form-section">
			<text>允许审核中再提交</text>
			<input v-model="allowResubmission" />
			<view class="switch-container" @tap="toggleLottery">
				<switch :checked="enableLottery" class="switch-checkbox" />
				<view class="slider round" :class="{'active': enableLottery}"></view>
			</view>
		</view>
		<view class="form-section">
			<text>单用户日提交次数</text>
			<input type="number" v-model="dailySubmissionsLimit" @blur="confirmModification"
				style="margin-left: 30px;" />
			<button class="modify-button" @tap="enableModification" style="width: 80px;">修改</button>
		</view>
		<button @click="submitAlldata">保存</button>
	</view>
</template>

<script>

	export default {
		data() {
			return {
				prizes: [{
						icon: '/static/logo.png',
						name: '免单'
					},
					{
						icon: '/static/logo.png',
						name: '外卖券'
					},
					{
						icon: '/static/logo.png',
						name: '神秘奖励'
					},
					{
						icon: '/static/logo.png',
						name: '外卖会员'
					},
					{
						icon: '',
						name: ''
					}, // 中间项
					{
						icon: '/static/logo.png',
						name: '随机红包'
					},
					{
						icon: '/static/logo.png',
						name: '最高红包'
					},
					{
						icon: '/static/logo.png',
						name: '最低红包'
					},
					{
						icon: '/static/logo.png',
						name: '点击图标设置奖项'
					}
				],
				highlightedIndex: null,
				isSpinning: false,
				spinSequence: [],
				spinInterval: null,
				enableLottery: false,
				storeInfo: '',
				contactPhone: '',
				storeAddress: '',
				contactPhoneEditMode: false,
				tempContactPhone: '',
				storeAddressEditMode: false,
				tempStoreAddress: '',
				submitPageSetting: 'default',
				lotteryOrderSetting: 'random', // 默认为随机
				maxSubmissionTimeHours: 12,
				dailySubmissionsLimit: 2,
				modificationEnabled: false,
				id: 0,
				storeId:0,
				ifactive:0,
			    iconUrl: '',
				prizeName: '随机红包',
				minAmount: '',
				maxAmount: '',
			}
		},
		onLoad(options) {
			this.id = options.status;
			console.log(this.id);
			this.askInitialData(this.id);
		},
		methods: {
			async askInitialData(id) { // 确保 id 作为参数传递进来
				try {
					const response = await new Promise((resolve, reject) => {
						uni.request({
							url: 'http://zhaoyang.nat300.top/store/find',
							method: 'POST',
							data: {
								id: id,
							},
							header: {
								'content-type': 'application/json' // 默认值
							},
							success:(res)=>{ 
								resolve(res);
								console.log(res.data);
								this.storeId = res.data.id;
								this.ifactive = res.data.isEnabled;
								this.tempContactPhone = res.data.phone;
								this.tempStoreAddress = res.data.address;
								this.dailySubmissionsLimit = res.data.submit;
								this.maxSubmissionTimeHours = res.data.reviewedAt;

								if(this.ifactive==1){
									this.enableLottery=true;
								}else{
									this.enableLottery=false;
								}
								console.log(this.storeId);
							},
							fail: reject
						});
					});
					console.log('POST 请求成功:',id);
					// this.storeId=id;
					uni.showToast({
						title: '提交成功',
						icon: 'success'
					});
					// 如果需要进一步处理响应数据，可以在这里进行
				} catch (error) {
					console.error('POST 请求失败:', error);
					uni.showToast({
						title: '提交失败，请重试',
						icon: 'none'
					});
				}
			},
			  spinRoulette(){
				  try {
				  		const response = new Promise((resolve, reject) => {
				  			uni.request({
				  				url: 'http://zhaoyang.nat300.top/store/find1',
				  				method: 'POST',
				  				data: {
									storeId:this.storeId,
				  					type: '随机红包',
				  				},
				  				header: {
				  					'content-type': 'application/json' // 默认值
				  				},
				  				success: resolve,
				  				fail: reject
				  			});
				  		});
				  
				  		console.log('POST 请求成功:', response);
				  		uni.showToast({
				  			title: '提交成功',
				  			icon: 'success'
				  		});
				  
				  		// 如果需要进一步处理响应数据，可以在这里进行
				  
				  	} catch (error) {
				  		console.error('POST 请求失败:', error);
				  		uni.showToast({
				  			title: '提交失败，请重试',
				  			icon: 'none'
				  		});
				  	}
				  },
				  
			handlePrizeClick(index, prize) {
				if (index === this.highlightedIndex) {
					uni.showModal({
						title: '提示',
						content: '弹框'
					})
				} else if (prize.name === '随机红包') {
					this.$refs.popupBottom.open()
					this.confirmSetPrize();
				}
			},
			confirmSetPrize(){
				uni.request({
					url: 'http://zhaoyang.nat300.top/store/find1',
					method: 'POST',
					data: {
						storeId:this.storeId,
						type: '随机红包',
						min:this.minAmount,
						max:this.maxAmount,
						auto:1,
						price:1
					},
					header: {
						'content-type': 'application/json' // 默认值
					},
					success:res=>{
						console.log(res);
						this.minAmount=res.data.minAmount;
						this.maxAmount=res.data.maxAmount;
					}
				});
			},
			confirmSetPrizeCon(){
				uni.request({
					url: 'http://zhaoyang.nat300.top/store/update2',
					method: 'POST',
					data: {
						storeId:this.storeId,
						type: '随机红包',
						min:this.minAmount,
						max:this.maxAmount,
						auto:1,
						price:1
					},
					header: {
						'content-type': 'application/json' // 默认值
					},
				});
			},
			getSpinSequence() {
				const sequence = [...Array(9).keys()]; // 包含所有格子的索引

				if (this.lotteryOrderSetting === 'random') {
					return sequence.sort(() => Math.random() - 0.5);
				} else { // 'sequential'
					return sequence; // 顺序排列
				}
			},
			toggleLottery() {
				this.enableLottery = !this.enableLottery;
				this.enableLottery ==true? this.ifactive=1:this.ifactive=0;
				if(this.ifactive==1){
					this.enableLottery=true;
				}else{
					this.enableLottery=false;
				}
			},
			toggleEditMode(field) {
				const editModeField = field + 'EditMode';
				this[editModeField] = !this[editModeField];
				if (this[editModeField]) {
					this['temp' + field.charAt(0).toUpperCase() + field.slice(1)] = this[field];
				}
			},
			navigateToEditStoreInfo() {
				uni.navigateTo({
					url: `/pages/storeinfo/storeinfo?status=${this.id}`
				})
			},
			enableModification() {
				this.modificationEnabled = true;
			},
			confirmModification() {
				if (this.modificationEnabled) {
					this.modificationEnabled = false;
				}
			},
			async submitAlldata(){
				try {
					const response = await new Promise((resolve, reject) => {
						   uni.request({
							url: 'http://zhaoyang.nat300.top/store/update',
							method: 'POST',
							data: {
								id:this.id,
								storeId:this.storeId,
								review: this.maxSubmissionTimeHours,
								address: this.tempStoreAddress,
								phone:this.tempContactPhone,
								submit:this.dailySubmissionsLimit,
								enabled:this.ifactive
							},
							header: {
								'content-type': 'application/json' // 默认值
							},
							success: resolve,
							fail: reject
						});
					});
					console.log('门店设置最后POST 请求成功:', response);
					uni.showToast({
						title: '提交成功',
						icon: 'success'
					});
					uni.navigateTo({
						url:`/pages/home/home?status=${this.id}`
					})
					// 如果需要进一步处理响应数据，可以在这里进行
				
				} catch (error) {
					console.error('POST 请求失败:', error);
					uni.showToast({
						title: '提交失败，请重试',
						icon: 'none'
					});
				}
			}
		}
		}
</script>
<style>
	
	.popup-content{
		background-color: white;
		padding:20rpx;
	}
	.form-item {
	  margin-bottom: 10px;
	  display: flex;
	  justify-content: space-between;
	  align-items: center;
	}
	
	.form-item input,
	.form-item switch {
	  margin-left: 10px;
	}
	
	.form-item image {
	  width: 50px;
	  height: 50px;
	}
	.store-settings {
		padding: 20px;
		font-family: Arial, sans-serif;
	}

	.toggle-section {
		margin-bottom: 20px;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.switch-container {
		position: relative;
		display: inline-block;
		width: 60px;
		height: 34px;
	}

	.switch-checkbox {
		opacity: 0;
		width: 0;
		height: 0;
	}

	.slider {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: #ccc;
		transition: .4s;
		border-radius: 34px;
	}

	.slider:before {
		position: absolute;
		content: "";
		height: 26px;
		width: 26px;
		left: 4px;
		bottom: 4px;
		background-color: white;
		transition: .4s;
		border-radius: 50%;
	}

	.slider.round {
		border-radius: 34px;
	}

	.slider.active {
		background-color: #4CAF50;
	}

	.slider.active:before {
		transform: translateX(26px);
	}

	.roulette-section {
		position: relative;
		margin-top: 20px;
		text-align: center;
	}

	.prize-grid {
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		gap: 10px;
		justify-content: center;
	}

	.prize-item {
		width: 100px;
		height: 100px;
		border-radius: 10px;
		background-color: #f9f9f9;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.prize-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 100%;
		height: 100%;
		padding: 10px;
		box-sizing: border-box;
	}

	.prize-img {
		width: 45px;
		height: 45px;
		margin-bottom: 8px;
		object-fit: contain;
	}

	.prize-name {
		font-size: 12px;
		color: #333;
		text-align: center;
		line-height: 1.2;
		word-break: break-all;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
	}

	.highlight {
		background-color: yellow;
	}

	.spin-button {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		z-index: 10;
		width: 100px;
		height: 40px;
		background-color: #f0f0f0;
		border: 1px solid #ccc;
		border-radius: 5px;
		font-size: 16px;
	}

	.form-section {
		display: flex;
		align-items: center;
		margin-bottom: 20px;
	}

	.form-input {
		margin-left: 10px;
		padding: 5px;
		border: 1px solid #ccc;
		border-radius: 4px;
	}

	.modify-button {
		background-color: #4CAF50;
		border: none;
		color: white;
		padding: 5px 10px;
		text-align: center;
		text-decoration: none;
		display: inline-block;
		font-size: 14px;
		margin: 4px 2px;
		border-radius: 5px;
	}

	.modify-button:hover {
		background-color: #45a049;
	}
</style>